﻿using System;
using System.Windows.Forms;
using SourceCodePlugin.Collections;

namespace SourceCodePlugin.Controls
{
    public partial class SourceCodeEditor : Form
    {
        private readonly Settings settings;
        
        private int currentTabSize;
        private int previousTabSize;

        public SourceCodeEditor(Settings settings)
        {
            this.settings = settings;
            this.currentTabSize = settings.TabSize;
            this.previousTabSize = settings.TabSize;

            InitializeComponent();
            SetupTabSizeList();
            SetupLanguageList();

            codeEditor.Text = settings.Code;
            codeEditor.AcceptsTab = true;
            codeEditor.AcceptsReturn = true;
            codeEditor.KeyDown += new KeyEventHandler(codeEditor_KeyDown);

            tabSizeList.SelectedValue = settings.TabSize;
            tabSizeList.SelectedValueChanged += new EventHandler(tabSizeList_SelectedValueChanged);

            languageList.SelectedValue = settings.Language;

            saveButton.Click += new EventHandler(saveButton_Click);
            cancelButton.Click += new EventHandler(cancelButton_Click);
            
        }

        void cancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        void codeEditor_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Tab)
            {
                codeEditor.TabKeyHandler(currentTabSize);
                e.SuppressKeyPress = true;
            }
        }

        void saveButton_Click(object sender, EventArgs e)
        {
            if (codeEditor.TextLength > 0)
            {
                settings.Code = codeEditor.Text;
                settings.TabSize = currentTabSize;
                settings.Language = languageList.SelectedValue.ToString();
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        void tabSizeList_SelectedValueChanged(object sender, EventArgs e)
        {
            previousTabSize = currentTabSize;
            currentTabSize = (int)tabSizeList.SelectedValue;

            codeEditor.TabSizeChanged(previousTabSize, currentTabSize);
        }
        
        void SetupTabSizeList()
        {
            tabSizeList.DataSource = TabSizeCollection.TabSizes;
            tabSizeList.DisplayMember = "Name";
            tabSizeList.ValueMember = "Value";
        }

        void SetupLanguageList()
        {
            languageList.DataSource = LanguageCollection.Languages;
            languageList.DisplayMember = "Name";
            languageList.ValueMember = "Value";
        }
    }
}
